const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static('.'));

// JWT密钥
const JWT_SECRET = 'your-secret-key-change-in-production';

// 模拟用户数据库
const users = [
    {
        id: 1,
        username: '李明',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码: password
        role: 'minister',
        department: '开发部'
    },
    {
        id: 2,
        username: '张三',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码: password
        role: 'pm',
        department: '项目管理部'
    },
    {
        id: 3,
        username: '李四',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码: password
        role: 'frontend',
        department: '前端开发部'
    },
    {
        id: 4,
        username: '王五',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码: password
        role: 'backend',
        department: '后端开发部'
    },
    {
        id: 5,
        username: '赵六',
        password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码: password
        role: 'member',
        department: '开发部'
    }
];

// 模拟项目数据库
const projects = [
    {
        id: 1001,
        name: "项目A",
        description: "这是一个重要的前端项目",
        status: "active",
        progress: 75,
        start_date: "2023-01-01",
        end_date: "2023-06-30",
        pm_id: 2,
        pm_name: "张三",
        git_url: "https://github.com/example/project-a",
        created_at: "2023-01-01 10:00:00",
        updated_at: "2023-05-15 15:30:00"
    },
    {
        id: 1002,
        name: "项目B",
        description: "后端API开发项目",
        status: "completed",
        progress: 100,
        start_date: "2023-02-01",
        end_date: "2023-04-30",
        pm_id: 4,
        pm_name: "王五",
        git_url: "https://github.com/example/project-b",
        created_at: "2023-02-01 09:00:00",
        updated_at: "2023-04-30 18:00:00"
    },
    {
        id: 1003,
        name: "项目C",
        description: "移动端应用开发",
        status: "paused",
        progress: 45,
        start_date: "2023-03-01",
        end_date: "2023-08-30",
        pm_id: 3,
        pm_name: "李四",
        git_url: "https://github.com/example/project-c",
        created_at: "2023-03-01 14:00:00",
        updated_at: "2023-05-10 11:20:00"
    },
    {
        id: 1004,
        name: "项目D",
        description: "数据分析平台",
        status: "active",
        progress: 30,
        start_date: "2023-04-01",
        end_date: "2023-09-30",
        pm_id: 2,
        pm_name: "张三",
        git_url: "https://github.com/example/project-d",
        created_at: "2023-04-01 16:00:00",
        updated_at: "2023-05-20 10:15:00"
    },
    {
        id: 1005,
        name: "项目E",
        description: "内部管理系统",
        status: "active",
        progress: 60,
        start_date: "2023-05-01",
        end_date: "2023-10-30",
        pm_id: 5,
        pm_name: "赵六",
        git_url: "https://github.com/example/project-e",
        created_at: "2023-05-01 13:00:00",
        updated_at: "2023-05-25 16:45:00"
    }
];

// 用户登录API
app.post('/auth/login', async (req, res) => {
    try {
        const { username, password } = req.body;

        // 验证请求参数
        if (!username || !password) {
            return res.status(400).json({
                code: 400,
                message: '用户名和密码不能为空',
                data: null
            });
        }

        // 查找用户
        const user = users.find(u => u.username === username);
        
        if (!user) {
            return res.status(401).json({
                code: 401,
                message: '用户名或密码错误',
                data: null
            });
        }

        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        
        if (!isPasswordValid) {
            return res.status(401).json({
                code: 401,
                message: '用户名或密码错误',
                data: null
            });
        }

        // 生成JWT token
        const token = jwt.sign(
            { 
                userId: user.id, 
                username: user.username, 
                role: user.role 
            },
            JWT_SECRET,
            { expiresIn: '24h' }
        );

        // 返回成功响应
        res.json({
            code: 200,
            message: '登录成功',
            data: {
                user_info: {
                    username: user.username,
                    role: user.role,
                    department: user.department
                },
                token: token
            }
        });

    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({
            code: 500,
            message: '服务器内部错误',
            data: null
        });
    }
});

// 验证token的中间件
const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({
            code: 401,
            message: '访问令牌缺失',
            data: null
        });
    }

    jwt.verify(token, JWT_SECRET, (err, user) => {
        if (err) {
            return res.status(403).json({
                code: 403,
                message: '访问令牌无效',
                data: null
            });
        }
        req.user = user;
        next();
    });
};

// 获取用户信息的API（需要认证）
app.get('/auth/user-info', authenticateToken, (req, res) => {
    const user = users.find(u => u.id === req.user.userId);
    
    if (!user) {
        return res.status(404).json({
            code: 404,
            message: '用户不存在',
            data: null
        });
    }

    res.json({
        code: 200,
        message: '获取用户信息成功',
        data: {
            user_info: {
                username: user.username,
                role: user.role,
                department: user.department
            }
        }
    });
});

// 获取项目列表API（需要认证）
app.get('/projects', authenticateToken, (req, res) => {
    try {
        const user = users.find(u => u.id === req.user.userId);
        
        if (!user) {
            return res.status(404).json({
                code: 404,
                message: '用户不存在',
                data: null
            });
        }

        let filteredProjects = [];

        // 根据用户角色过滤项目
        if (user.role === 'minister') {
            // 部长可以查看所有项目
            filteredProjects = projects;
        } else {
            // 其他用户只能查看自己负责的项目
            filteredProjects = projects.filter(project => project.pm_id === user.id);
        }

        res.json({
            code: 200,
            message: '获取成功',
            data: filteredProjects
        });

    } catch (error) {
        console.error('获取项目列表错误:', error);
        res.status(500).json({
            code: 500,
            message: '服务器内部错误',
            data: null
        });
    }
});

// 测试路由
app.get('/api/test', (req, res) => {
    res.json({
        code: 200,
        message: 'API服务器运行正常',
        data: {
            timestamp: new Date().toISOString()
        }
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('可用的测试用户:');
    users.forEach(user => {
        console.log(`用户名: ${user.username}, 角色: ${user.role}, 部门: ${user.department}`);
    });
    console.log('所有用户的密码都是: password');
}); 